<?php
require_once 'models/order.inc';
require_once 'models/TMSACL.inc';

class TMSCartPositionItem extends TCandyItem {
	public function __get($nm){
		switch ($nm){
			case 'Price':return $this->Product->OrderPrice(false,$this);break;
			case 'Cost':return $this->Price*$this->Quantaty;break;
			default:return parent::__get($nm);break;
		}
	}
		
	protected function checkProperties(){
		parent::checkProperties();
		$opts = $this->Product->OrderOptions($this);
		foreach ($opts as $nm=>$opt)
			$this->properties[$nm] = new TCandyItemProperty($this, $opt);
	}
}

class TMSCartModel extends TCandyModel {
/**
 * @var TMSACL
 */	
	protected $_ioc_acl_;
	
	protected function afterConstruct(){
		$this->_conf_classname_ = 'TMSCartPosition';	
		$this->_array_id_properties_ = array('Product','DataHash');
	}
	
	public function MakeEmpty(){
		$u = $this->Acl->CurrentUser();
		if ($u instanceof TMSUser){
			if (!($u->Roles && TMSRole::CLIENT))
				throw new TCoreException(TCoreException::ERR_ACCESS_DENIED);
		} else 
			throw new TCoreException(TCoreException::ERR_ACCESS_DENIED);
		$this->Adapter->Driver->Execute('delete from cart_position where client = :uid',array('uid'=>$u->Id));
	}
	
	private function assignOptions($options, $data){
		foreach ($data as $nm => $v)
			if ($nm != 'Client' && $nm != 'Product' && $nm != 'Data' && $nm != 'DataHash')
				$options[$nm] = $v;
		
		$data['Data'] = json_encode($options);	
		return array_diff($data, $options);	
	}
	
	protected function preCreateItem(array $data, $class = null){
		return $this->assignOptions(array());
	}
	
	protected function preEditItem($id,array $data, $origin){
		return $this->assignOptions($origin->Options());
	}	
	
	protected function beforeSave(TNOrmObject $object){
		if (!$object->Data)
			$object->DataHash = '';
		return $object;
	}
	
	protected function getDummy($id = null, $class = null){
		$dummy = parent::getDummy($id, $class);
		$u = $this->Acl->CurrentUser();
		if (!$dummy->Client){
			if ($u instanceof TMSUser){
				if ($u->Roles && TMSRole::CLIENT)
					$dummy->Client = $u->Id;
				else
					throw new TCoreException(TCoreException::ERR_ACCESS_DENIED);	
			}
		} 
		$dummy->DataHash = '';
		return $dummy;
	}
	
/**
 * @param object $object
 * @return TCandyItem
 */
	public function WrapObject($object, array &$caller_stack = array()){
		if ($object instanceof $this->_conf_classname_)
			return new TMSCartPositionItem($object,$this);
		return parent::WrapObject($object,$caller_stack);
	}	
}